<template>
    <el-main>
        <el-form :model="searchParm" inline="true" size="default">
            <el-form-item>
                <el-input style="width: 200px;" placeholder="请输入关键字" v-model="fileKeyWord"></el-input>
                <el-button style="margin-left: 10px;" icon="Search" @click="searchFile">搜索</el-button>
            </el-form-item>
            <el-form-item>
                <el-upload style="display: flex;" :v-loading="loading" action="" :show-file-list="false"
                    :auto-upload="false" :on-change="handleChange">
                    <template #trigger>
                        <el-button icon="UploadFilled" type="primary" @click="fileUpload">文件上传</el-button>
                    </template>
                    <el-button style="margin-left: 10px;" icon="FolderAdd" type="warning"
                        @click="createDir">新建文件夹</el-button>
                    <el-button icon="Delete" type="danger">批量删除</el-button>
                </el-upload>
            </el-form-item>
        </el-form>

        <!--目录-->
        <div v-show="searchParm.op === 1">
            <div style="float: left">
                <el-link type="primary" icon="HomeFilled" @click="toIndexDir" :underline="false">主目录</el-link>
                <el-link v-for="item in dirList" type="primary" icon="ArrowRight" @click="enterDirById(item.fileName)"
                    :underline="false">{{ item.fileName }}
                </el-link>
            </div>
            <div v-show="dirList.length != 0" style="float: right">
                <el-link type="primary" icon="Back" @click="returnDir">返回</el-link>
            </div>
        </div>
        <!-- <div v-show="searchParm.op === 2" style="float: left">
            <el-link type="danger" icon="el-icon-delete-solid" @click="deleteAllForever"
                :underline="false">删除所有文件</el-link>
        </div> -->

        <!-- 表格 -->
        <el-table style="margin-top: 20px;width: 100%;" :height="tableHeight" default-expand-all :data="tableList"
            border stripe @selection-change="handleSelectionChange">
            <el-table-column label="id" v-if="false" prop="id"></el-table-column>
            <el-table-column type="selection"></el-table-column>
            <el-table-column label="文件名" prop="fileName">
                <template #default="{ row }">
                    <div style="display: flex; justify-content: space-between; align-items: center;"
                        @mouseenter="row.isHovered = true" @mouseleave="row.isHovered = false">
                        <el-link type="primary" @click="handleFileNameClick(row)">{{ row.fileName }}</el-link>
                        <div v-if="row.isHovered && row.fileType !== '文件夹'">
                            <el-tooltip content="下载" placement="top">
                                <el-link icon="Download" @click="handleDownload(row)"
                                    style="cursor: pointer;"></el-link>
                            </el-tooltip>
                            <el-tooltip content="分享" placement="top">
                                <el-link icon="Share" @click="handleShare(row)"
                                    style="cursor: pointer; margin-left: 10px;"></el-link>
                            </el-tooltip>
                        </div>
                    </div>
                </template>
                <template v-slot="scope" v-if="showCreateDir">
                    <div v-if="scope.$index === 0">
                        <el-input v-model="newFolderName" placeholder="输入文件夹名称" style="width: 35%;"></el-input>
                        <el-button style="margin-left: 10px;" type="success"
                            @click="confirmFolder(scope.row)">确定</el-button>
                        <el-button type="danger" @click="cancelFolder">取消</el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="文件类型" width="180" prop="fileType"></el-table-column>
            <el-table-column label="大小(kb)" width="180" prop="fileSize"></el-table-column>
            <el-table-column label="修改时间" prop="createTime"></el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @size-change="sizeChange" @current-change="currentChange"
            :current-page.sync="searchParm.currentPage" :page-sizes="[10, 20, 40, 80, 100]"
            :page-size="searchParm.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="searchParm.total"
            background>
        </el-pagination>

    </el-main>
</template>

<script setup lang="ts">
import { ElMessage, UploadFile, UploadFiles } from 'element-plus';
import { ref, reactive, onMounted, nextTick } from 'vue';
import { createDirType, getByFileNameParm } from "@/api/document/DocumentModel";
import { createDirApi, getListApi, uploadFileApi, downloadFileApi, getByFileNameApi } from "@/api/document/index";
import { userStore } from "@/store/user";
import { Base64 } from "js-base64";
const store = userStore();
const fileKeyWord = ref('');
const showCreateDir = ref(false);
const loading = ref(false);
const dirList = ref<any[]>([]);

interface fileType {

}
const multipleSelection = ref<fileType[]>([]);

//表单绑定的对象
const searchParm = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0,
    curDir: "",
    op: 1,
});
const handleSelectionChange = (val: fileType[]) => {
    multipleSelection.value = val;
}
//页容量改变时触发
const sizeChange = (size: number) => {
    searchParm.pageSize = size;
    getList();
};
//页数改变时触发
const currentChange = (page: number) => {
    searchParm.currentPage = page;
    getList();
};

//表格数据
const tableList = ref<any[]>([]);
//查询列表
const getList = async () => {
    let res = await getListApi(searchParm);
    if (res && res.code == 200) {
        //设置表格数据
        tableList.value = res.data.records;
        tableList.value = res.data.records.map((record: any) => {
            return {
                ...record,
                createTime: formatCreateTime(record.createTime)
            }
        })
        //设置分页总条数
        searchParm.total = res.data.total;
    }
};
const formatCreateTime = (createTime: string): string => {
    const date = new Date(createTime);
    const formattedDate = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    return formattedDate;
}

//表格高度
const tableHeight = ref(0);
const newFolderName = ref('')
//新建文件夹
const createDir = () => {
    showCreateDir.value = true;
    tableList.value.unshift({});
    newFolderName.value = ''
}
//确定新建文件夹
const confirmFolder = async (row: createDirType) => {
    if (newFolderName.value.trim() !== '') {
        row = {
            curDir: searchParm.curDir !== '' ? searchParm.curDir : '/',
            dirName: newFolderName.value,
            creator: store.getNickName,
        }
        let res = await createDirApi(row);
        if (res && res.code == 200) {
            tableList.value.shift();
            showCreateDir.value = false;
            getList();//刷新列表
        }
    }
    else {
        ElMessage.error("请输入文件夹名称！")
    }
}
//取消新建文件夹
const cancelFolder = () => {
    // 取消新建文件夹，移除新建行的数据并隐藏输入框  
    tableList.value.shift();
    newFolderName.value = ''
    showCreateDir.value = false;
}

const uploadFileList = ref<any[]>([]);
//上传文件
const fileUpload = () => {
    uploadFileList.value = [];
}
const handleChange = (file: UploadFile, fileList: UploadFiles) => {
    console.log("文件列表：", file, fileList);
    uploadFileList.value = fileList;
    if (uploadFileList.value.length !== 0) {
        let formData = new FormData();
        formData.append("uploadFile", uploadFileList.value[0].raw)//拿到存在fileList的文件存放到formData中
        formData.append("curDir", searchParm.curDir);
        formData.append("creator", store.getNickName);
        uploadFiles(formData);
    }
    fileList = [];
}
const uploadFiles = async (formData: FormData) => {
    loading.value = true;
    let res = await uploadFileApi(formData);
    if (res && res.code == 200) {
        getList();
        loading.value = false;
    }
}


//文件下载图标按钮事件
const handleDownload = async (row: any) => {

    downloadFileApi(row.id).then(res => {
        const blob = new Blob([res.data]);
        const elink = document.createElement('a');
        elink.download = row.fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
    })
}
//文件分享图标按钮事件
const handleShare = (row: any) => {
    console.log('分享文件：' + row.fileName);
}
//进入文件夹
const handleFileNameClick = (row: any) => {
    if (row.fileType == "文件夹") {
        dirList.value.push({ fileName: row.fileName, returnDirCurPage: searchParm.currentPage });
        searchParm.curDir += "/" + row.fileName;
        getList();
    }
    else {
        var url = ''; //要预览文件的访问地址
        window.open('http://127.0.0.1:8012/onlinePreview?url=' + encodeURIComponent(Base64.encode(url)));
    }
}
//进入主目录
const toIndexDir = () => {
    searchParm.curDir = '';
    dirList.value = [];
    getList();
}
//进入指定目录
const enterDirById = (_fileName: string) => {
    let list = ref<any[]>([]);
    searchParm.curDir = '';
    for (var { fileName } of dirList.value) {
        searchParm.curDir += "/" + fileName
        console.log('curDir=' + searchParm.curDir);
        list.value.push({ fileName })
        if (fileName === _fileName)
            break;
    }
    dirList.value = list.value;
    getList();
}
//返回上一级目录
const returnDir = () => {
    let popDir = dirList.value.pop();
    if (dirList.value.length === 0) {
        searchParm.curDir = ''
    } else {
        searchParm.curDir = searchParm.curDir.substring(0, searchParm.curDir.length - (popDir.fileName.length + 1))
    }
    getList();
}

//搜索文件
const searchFile = async () => {
    if (fileKeyWord.value !== '') {
        const row: getByFileNameParm = {
            pageNum: 1,
            pageSize: 10,
            fileName: fileKeyWord.value
        };
        let res = await getByFileNameApi(row);
        if (res && res.code == 200) {
            //设置表格数据
            tableList.value = res.data.records;
            tableList.value = res.data.records.map((record: any) => {
                return {
                    ...record,
                    createTime: formatCreateTime(record.createTime)
                }
            })
            //设置分页总条数
            searchParm.total = res.data.total;
        }
    } else {
        ElMessage.error("请输入正确文件名！")
    }
    fileKeyWord.value = '';
}

onMounted(() => {
    nextTick(() => {
        tableHeight.value = window.innerHeight - 230;
    })
    getList();
})


</script>

<style scoped>
.horizontal-form-item {
    display: flex;
    align-items: center;
    /* 垂直居中 */
}
</style>